/**
 *@category 
 *@author 邱磊
 *@date 2015年12月19日 下午2:54:49
 */
package com.hsnn.medstgmini.pro.base.dao.Impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.service.StdCompinfoManager;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.pro.base.dao.BaseDelAreaRelDao;
import com.hsnn.medstgmini.pro.base.model.form.BaseDelrelationForm;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.Pagination;

/**
 *@category 
 *@author 邱磊
 *@date 2015年12月19日 下午2:54:49
 *@param 
 */
@Repository
public class BaseDelAreaRelDaoImpl implements BaseDelAreaRelDao {
	@Autowired
	private HibernateSqlUtil dao;
	@Value("#{sysProp['system.province']}")
    private String sysProvince;
	@Value("#{projareaProp['projarea.enable']}")
    private String enable;
	@Value("#{projareaProp['projarea.GZJYCG_1']}")
    private String GZJYCG_1;
	@Value("#{projareaProp['projarea.GZJYCG_2']}")
    private String GZJYCG_2;
	@Autowired
	private StdCompinfoManager compManager;
	
	public Pagination getBaseDelAreaRelListCenterData(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append("select a.base_del_area_rel_id baseDelAreaRelId,")
		.append("a.del_comp_name delCompName,a.ar_fullname arFullName")
		.append("  from base_del_area_rel a")
		.append(" where a.status = :status");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", Constants.DEL_SELECT_STATUS_LINXUANTONGUO);
		if (StringUtils.isNotBlank(page.getConditions().get("compName"))){
			sql.append(" and (a.del_comp_name like :delCompName or a.del_comp_name_spel like :delCompNameSpel)");
			params.put("delCompName", "%" + page.getConditions().get("compName").trim() + "%");
			params.put("delCompNameSpel", "%" + page.getConditions().get("compName").trim().toUpperCase() + "%");
		}
		if (StringUtils.isNotBlank(page.getConditions().get("areaName"))){
			sql.append(" and a.ar_fullname like :areaName");
			params.put("areaName", "%" + page.getConditions().get("areaName").trim() + "%");
		}
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}
	public Pagination getAreaList(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append("select t.area_id,t.area_name,t.ar_fullname,t.ar_shortname,t.father_id,a.area_name father_name from dic_area t")
		.append(" left join dic_area a on a.area_id=t.father_id")
		.append("  where t.area_id like :province and t.area_id not like '%00'")
		.append(" and t.area_id not in ")
		.append(" (select b.area_code from base_del_area_rel b where b.del_comp_code=:delCompCode)");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("province", sysProvince.substring(0,2) + "%");
		params.put("delCompCode", page.getConditions().get("compCode"));
		if (StringUtils.isNotBlank(page.getConditions().get("fatherCode"))){
			sql.append(" and t.father_id = :fatherCode");
			params.put("fatherCode", page.getConditions().get("fatherCode").trim());
		}
		if (StringUtils.isNotBlank(page.getConditions().get("areaName"))){
			sql.append(" and t.area_name like :areaName");
			params.put("areaName", "%" + page.getConditions().get("areaName").trim() + "%");
		}
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}
	public void saveDelArea(Pagination page, List<String> areaIds){
		if ("1".equals(enable)){
			String[] proj1 = GZJYCG_1.split(",");
			String[] proj2 = GZJYCG_2.split(",");
			boolean sn = false;
			boolean sw = false;
			for (int i = 0; i < areaIds.size(); i ++){
				if (!sn){
					for (int j = 0; j < proj1.length; j ++){
						String areaCode = areaIds.get(i).substring(0,areaIds.get(i).length() - 2);
						String snArea = proj1[j].substring(0,proj1[j].length() -2);
						if (areaCode.equals(snArea)){
							sn = true;
							break;
						}
					}
				}
				
				if (!sw){
					for (int j = 0; j < proj2.length; j ++){
						String areaCode = areaIds.get(i).substring(0,areaIds.get(i).length() - 2);
						String swArea = proj2[j].substring(0,proj2[j].length() -2);
						if (areaCode.equals(swArea)){
							sw = true;
							break;
						}
					}
				}
			}
			Map<String, Object> comp = compManager.getCompinfoByCode(page.getConditions().get("compCode"));
			StringBuffer sql = new StringBuffer()
			.append("insert into base_del_area_rel select UUID(),a.area_id,a.area_name,a.ar_shortname,a.ar_fullname,:delCompCode,:delCompName,:delCompNameSpel,:delCompNameShort,")
			.append(" :delCompStatus,2,:delRange,:selUser,:selDatetime,:updUser,:updDatetime from dic_area a WHERE area_id in (:areaId)");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("delCompCode", comp.get("comp_code"));
			params.put("delCompName", comp.get("comp_name"));
			params.put("delCompNameSpel", comp.get("comp_spel_code"));
			params.put("delCompStatus", comp.get("status"));
			params.put("delCompNameShort", comp.get("comp_short_name"));
			params.put("delRange", Constants.DEL_RANGE_ALL);
			params.put("selUser", page.getConditions().get("user"));
			params.put("selDatetime", new Date());
			params.put("updUser", page.getConditions().get("user"));
			params.put("updDatetime", new Date());
			params.put("areaId", areaIds);
			dao.executeSql(sql.toString(), params);
			StringBuffer pc = new StringBuffer()
			.append("insert into bid_projcompany")
			.append(" select :uuid,t.proj_id,t.name,t.starttime,t.endtime,t.status,:delCompCode,null,1,:updDatetime,:updUser ")
			.append(" from bid_project t ")
			.append(" where not exists (select * from bid_projcompany a where a.proj_id=t.proj_id and a.comp_code=:delCompCode)")
			.append(" and t.proj_id = :projId");
			params.remove("delCompName");
			params.remove("delCompNameSpel");
			params.remove("delCompStatus");
			params.remove("delRange");
			params.remove("selUser");
			params.remove("selDatetime");
			params.remove("areaId");
			params.remove("delCompNameShort");
			String logsql = "insert into bid_projcompany_log select UUID(),t.* from bid_projcompany t where t.proj_del_id=:projDelId";
			Map<String, Object> logpm = new HashMap<String, Object>();
			if (sn){
				String uuid = UUID.randomUUID().toString();
				params.put("uuid", uuid);
				params.put("projId", Constants.SHENNEIXIANGMU);
				dao.executeSql(pc.toString(), params);
				logpm.put("projDelId", uuid);
				dao.executeSql(logsql, logpm);
			}
			if (sw){
				String uuid = UUID.randomUUID().toString();
				params.put("uuid", uuid);
				params.put("projId", Constants.SHENWAIXIANGMU);
				dao.executeSql(pc.toString(), params);
				logpm.put("projDelId", uuid);
				dao.executeSql(logsql, logpm);
			}
		}
	}
	public void deleteDelArea(List<BaseDelrelationForm> list, SysUser user){//些处删除采购目录不记录采购目录目志
		if (null != list && list.size() > 0){
			Map<String, Object> params = new HashMap<String, Object>();
			String sql = "";
			StringBuffer catalogsql = null;
			StringBuffer plansql = null;
			for (int i = 0; i < list.size(); i++){
				params.clear();
				BaseDelrelationForm form = list.get(i);
				Map<String, Object> map = this.getBaseDelAreaRelById(form.getDelRelId());
				sql = "DELETE from base_del_area_rel where base_del_area_rel_id = :id";
				params.put("id", form.getDelRelId());
				dao.executeSql(sql, params);
				catalogsql = new StringBuffer()
				.append("DELETE from pur_hospcatalog  where exists (")
				.append("select t.hosp_code from std_hospinfo t where t.hosp_code=hosp_code and t.area_id=:areaCode")
				.append(" ) and del_comp_code=:compCode");
				params.remove("id");
				params.put("areaCode", map.get("area_code"));
				params.put("compCode", map.get("del_comp_code"));
				dao.executeSql(catalogsql.toString(), params);
				plansql = new StringBuffer()
				.append("DELETE from pur_purplan  where exists (")
				.append("select t.hosp_code from std_hospinfo t where t.hosp_code=hosp_code and t.area_id=:areaCode")
				.append(" ) and del_comp_code=:compCode");
				params.remove("id");
				params.put("areaCode", map.get("area_code"));
				params.put("compCode", map.get("del_comp_code"));
				dao.executeSql(plansql.toString(), params);
			}
		}
	}
	
	public Map<String, Object> getBaseDelAreaRelById(String id){
		String sql = "select * from base_del_area_rel where base_del_area_rel_id = :id";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql, params);
		if (null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	
	@Override
	public Pagination getAreaListWithCity(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append("select t.area_id,t.area_name,t.ar_fullname,t.ar_shortname from dic_area t")
		.append("  where t.area_id like :province and t.area_id not like '%0000' and t.area_id like '%00' ")
		.append(" and t.area_id not in ")
		.append(" (select b.area_code from base_del_area_rel b where b.del_comp_code=:delCompCode)");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("province", sysProvince.substring(0,2) + "%");
		params.put("delCompCode", page.getConditions().get("compCode"));
		if (StringUtils.isNotBlank(page.getConditions().get("fatherCode"))){
			sql.append(" and t.father_id = :fatherCode");
			params.put("fatherCode", page.getConditions().get("fatherCode").trim());
		}
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}
}
